package com.siecom.tool;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.util.Log;

import com.siecom.constconfig.ConstDefine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


/**
 * 日志工具，所有的日志用此工具输出
 */
public class LogUtil {
    @SuppressLint("SimpleDateFormat")
    public static SimpleDateFormat format = new SimpleDateFormat("yyMMddHH");
    @SuppressLint("SimpleDateFormat")
    public static SimpleDateFormat formatSFM = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
    private static final String TAG = "LogUtil";

    private static boolean DEBUG = true;
    private static boolean LOG = true;
    public static LogRunable logRunable;

    public static void setDebug(boolean debug) {
        LogUtil.DEBUG = debug;
    }
    public static void setLog(boolean log){
        LogUtil.LOG = log;
    }

    public static void v(String tag, String msg) {
        if (DEBUG) {
            Log.v(tag, msg);
        }
    }

    public static void d(String tag, String msg) {
        d(tag, msg, null);
    }

    public static void d(String tag, String msg, Throwable tr) {
        if (DEBUG) {
            Log.d(tag, msg, tr);
        }
    }

    public static void i(String tag, String msg) {
        if (DEBUG) {
            Log.i(tag, msg);
        }
    }

    public static void w(String tag, String msg) {
        if (DEBUG) {
            Log.w(tag, msg);
        }
    }

    public static void e(String tag, String msg) {
        if (DEBUG) {
            e(tag, msg, null);
            if (LOG)
                save(msg,"a1testLog");
        }
    }

    public static void e(String tag, String msg, Throwable tr) {
        if (DEBUG) {
            Log.e(tag, msg, tr);
        }
    }

    public static void println(String str) {
        if (DEBUG) {
            System.out.println(str);
        }
    }

    /**
     * 把日志写入到本地文件
     * @param tag
     * @param msg
     * @param module
     */
    public static void i(String tag, String msg,String module) {
        if (LOG) {
            Log.i(tag, msg);
            logRunable = new LogRunable(tag+ ":" + msg ,module);
            SingletonThreadPool.getInstance().execute(logRunable);
        }
    }


//    public static void main(String args[]){
//
//        String ss = "aaaa";
//
//        save(ss,"IDCard");
//        save(ss,"Finger");
//
//        save(ss,"IDCard");
//        save("2222222","Finger");
//    }

    public static void save(String infoStr,String module){

        logRunable = new LogRunable(infoStr,module);
        SingletonThreadPool.getInstance().execute(logRunable);
    }

    public static synchronized String saveInfo2File(String infoStr,String module) {
        StringBuffer sb = new StringBuffer();
        sb.append("\n");
        sb.append(formatSFM.format(new Date()));
        sb.append("  ");
        sb.append(infoStr);

        String time = format.format(new Date());
        String fileName = time   + ".txt";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                File dir = new File(ConstDefine.LOG_DIR + module);

//                File dir = new File("D:\\A218Log\\" + module);
//                LogUtil.i(TAG, dir.toString());
                if (!dir.exists())
                    dir.mkdirs();
                FileOutputStream fos = new FileOutputStream(new File(dir, fileName),
                        true);
//                long size = CrashHandler.getFolderSize(dir);
//                System.out.println("size=" + size);

                File file = new File(dir.getAbsolutePath());
                if(file.isDirectory()){
                    File[] files = file.listFiles();
                    if (files.length > 10){
                        //排序
                        List fileList = Arrays.asList(files);
                        Collections.sort(fileList, new Comparator<File>() {
                            @Override
                            public int compare(File o1, File o2) {
                                if (o1.isDirectory() && o2.isFile())
                                    return -1;
                                if (o1.isFile() && o2.isDirectory())
                                    return 1;
                                return o1.getName().compareTo(o2.getName());
                            }
                        });
//                    for (int i = 0; i < files.length; i++) {
//                        System.out.println("文件："+ i + " "+files[i].getName());
//                    }
                        for(int i = 0;i < (files.length - 10);i++){
                            System.out.println("删除文件："+ i + " "+files[i].getName());
                            files[i].delete();
                        }
                    }

                }
//                if (size > 104857600) {
//                    CrashHandler.deleteFolderFile(dir.getAbsolutePath(),false);
//                }
                fos.write(sb.toString().getBytes());
                fos.close();
                return sb.toString();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static class LogRunable implements Runnable {

        public String logStr;
        public String module;
        public LogRunable(String str,String module){
            this.logStr = str;
            this.module = module;
        }
        @Override
        public void run() {
            saveInfo2File(logStr,module);
        }
    }

}
